"""
代码尝试专用脚本（空壳模板）
- 用于调试、测试新功能或片段
"""

import time
import yaml
import os
import pandas as pd
import numpy as np
import networkx as nx
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
from scipy.stats import kruskal, f_oneway
from src.mgm import (
    preprocess_data,
    add_age_group,
    bootstrap_diff,
    build_network_from_adj,
    compare_network_structure,
    draw_multi_year_agegroup_networks,
    draw_multi_year_networks,
    draw_network,
    draw_network_subplot,
    filter_vars,
    get_chinese_name,
    get_network_annotation,
    get_node_metrics,
    get_stable_edges,
    plot_density_heatmap,
    plot_happiness_centrality_bar,
    print_node_metrics,
    run_ledoitwolf,
    run_mgm,
    save_and_show_fig,
    test_edge_weight_diff,
    test_node_centrality_diff,
)
from utils.plot_style import setup_chinese_font, set_plot_style, force_chinese_font

with open(os.path.join(os.path.dirname(__file__), 'config.yaml'), encoding='utf-8') as f:
    config = yaml.safe_load(f)
ch_font = FontProperties(family=config.get('ch_font', 'Heiti TC'))
CORE_NAME_MAP = config.get('core_name_map_mgm', {})

# 全局中文字体和绘图风格设置
set_plot_style(config.get('output', {}).get('figures', {}))

if __name__ == "__main__":
    print("=" * 40)
    start_time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    start_time = time.time()
    print(f"⏱ 代码尝试开始 {start_time_str}")
    print("=" * 40)
    setup_chinese_font()


    # 参数集中管理
    params = {
        'csv_path': config.get('csv_path', 'data/CGSS三年.csv'),
        'figures_dir': config.get('figures_dir', 'figures'),
        'fields_core': list(CORE_NAME_MAP.keys()),
        'control_vars': [
            "年龄", "教育程度",
            "个人实际年收入对数", "家庭实际人均收入对数",
            "高等教育标识", "工作强度标识","区县",
            "年份"
        ],
        'mgm_alpha': float(config.get('mgm', {}).get('mgm_alpha', 0.05)),
        'edge_threshold': float(config.get('mgm', {}).get('edge_threshold', 0.05)),
        'unique_min': int(config.get('mgm', {}).get('unique_min', 2)),
        'std_min': float(config.get('mgm', {}).get('std_min', 1e-6))
    }
    df = pd.read_csv(params['csv_path'], low_memory=False)
    df = df[df["城乡"].astype(str).str.strip() == "城市"].copy()
    missing_cols = [col for col in params['fields_core'] + params['control_vars'] if col not in df.columns]
    if missing_cols:
        print("缺失的列：", missing_cols)
    df_net = preprocess_data(df, params['fields_core'], params['control_vars'])
    df_net = add_age_group(df_net)  # 新增：添加年龄组

     # 统一收集图片路径
    img_paths = []

    # 全样本建模和绘图
    adj, var_names = run_mgm(df_net, params['fields_core'], params['control_vars'], alpha=params['mgm_alpha'])
    G = build_network_from_adj(adj, var_names, df_net, threshold=params['edge_threshold'])
    net_img_path = os.path.join(params['figures_dir'], "MGM_混合图模型网络.png")
    draw_network(G, "MGM混合图模型网络", net_img_path, ch_font, params, node_color='skyblue')
    img_paths.append(net_img_path)
    print(print_node_metrics(G))

    multi_year_img_path = os.path.join(params['figures_dir'], "分年份网络合并图.png")
    node_metrics_all, year_networks = draw_multi_year_networks(
        df_net, params['fields_core'], params['control_vars'], ch_font, multi_year_img_path, params
    )
    img_paths.append(multi_year_img_path)
    # 新增：调用检验函数
    test_node_centrality_diff(node_metrics_all, "幸福感")
    test_edge_weight_diff(year_networks, ("幸福感", "年龄"))
    # 批量检验所有核心节点的中心性变化
    core_nodes = ["幸福感", "地位", "社会资本", "节俭", "公平感", "年龄", "教育", "个人收入", "人均收入", "大学", "工作强度"]
    for node in core_nodes:
        test_node_centrality_diff(node_metrics_all, node)
    
    stable_edges = get_stable_edges(year_networks)
    for edge in stable_edges:
        test_edge_weight_diff(year_networks, edge)

    # 年龄组分层网络分析
    if "年龄组" in df_net.columns:
        print("\n==== 按年份分层的年龄组网络分析 ====")
        agegroup_img_path = os.path.join(params['figures_dir'], "分年份年龄组网络合并图.png")
        results, df_summary = draw_multi_year_agegroup_networks(
            df_net, params['fields_core'], params['control_vars'], ch_font, agegroup_img_path, params
        )
        img_paths.append(agegroup_img_path)

     # 新增：网络密度热力图
    density_heatmap_path = os.path.join(params['figures_dir'], "网络密度热力图.png")
    plot_density_heatmap(df_summary, save_path=density_heatmap_path)
    img_paths.append(density_heatmap_path)

    # 新增：幸福感中心性条形图
    happiness_centrality_path = os.path.join(params['figures_dir'], "幸福感中心性条形图.png")
    plot_happiness_centrality_bar(df_summary, results, save_path=happiness_centrality_path)
    img_paths.append(happiness_centrality_path)

    # 统计分析：同一变量不同层级间的差异
    print("\n==== 统计分析：同一变量不同层级间的差异 ====")
    for var in params['fields_core']:
        if var == "幸福感":
            continue
        print(f"\n变量【{var}】各层级统计：")
        for year, G in year_networks:
            if G.has_node(var):
                values = [G.nodes[node].get(var) for node in G.nodes() if var in G.nodes[node]]
                print(f"{year}年 {var}：均值={np.mean(values):.3f}, 方差={np.var(values):.3f}")

    # 年龄组与幸福感的关系
    print("\n==== 年龄组与幸福感的关系 ====")
    for year, G in year_networks:
        if G.has_node("幸福感"):
            age_groups = [G.nodes[node].get("年龄组") for node in G.nodes() if "年龄组" in G.nodes[node]]
            happiness = [G.nodes[node].get("幸福感") for node in G.nodes() if "幸福感" in G.nodes[node]]
            if len(set(age_groups)) > 1:
                stat, p = kruskal(*[np.array(happiness)[np.array(age_groups) == ag] for ag in set(age_groups)])
                print(f"{year}年 不同年龄组间幸福感差异检验 p值：{p:.3f}")

    # 组内比较：同一年份不同年龄组
    print("\n==== 组内比较：同一年份不同年龄组 ====")
    for year in sorted(df_summary["年份"].unique()):
        sub = df_summary[df_summary["年份"] == year]
        # 幸福感介数中心性
        centralities = []
        for age_group in sub["年龄组"]:
            G = results.get((year, age_group))
            if G and "幸福感" in G.nodes:
                c = nx.betweenness_centrality(G)["幸福感"]
                centralities.append((age_group, c))
        if len(centralities) > 1:
            vals = [v for _, v in centralities]
            print(f"\n{year}年各年龄组幸福感介数中心性：{dict(centralities)}")
            try:
                stat, p = f_oneway(*[[v] for _, v in centralities])
            except Exception:
                stat, p = kruskal(*[[v] for _, v in centralities])
            print(f"{year}年幸福感介数中心性组间差异检验 p值：{p:.3f}")
        # 网络密度
        densities = sub["网络密度"].values
        if len(densities) > 1:
            print(f"{year}年各年龄组网络密度：{dict(zip(sub['年龄组'], densities))}")
            try:
                stat, p = f_oneway(*[[d] for d in densities])
            except Exception:
                stat, p = kruskal(*[[d] for d in densities])
            print(f"{year}年网络密度组间差异检验 p值：{p:.3f}")

    # 组间比较：同一年龄组不同年份
    print("\n==== 组间比较：同一年龄组不同年份 ====")
    for age_group in sorted(df_summary["年龄组"].unique()):
        sub = df_summary[df_summary["年龄组"] == age_group]
        # 幸福感介数中心性
        centralities = []
        for year in sub["年份"]:
            G = results.get((year, age_group))
            if G and "幸福感" in G.nodes:
                c = nx.betweenness_centrality(G)["幸福感"]
                centralities.append((year, c))
        if len(centralities) > 1:
            vals = [v for _, v in centralities]
            print(f"\n年龄组{age_group}各年份幸福感介数中心性：{dict(centralities)}")
            try:
                stat, p = f_oneway(*[[v] for _, v in centralities])
            except Exception:
                stat, p = kruskal(*[[v] for _, v in centralities])
            print(f"年龄组{age_group}幸福感介数中心性组间差异检验 p值：{p:.3f}")
        # 网络密度
        densities = sub["网络密度"].values
        if len(densities) > 1:
            print(f"年龄组{age_group}各年份网络密度：{dict(zip(sub['年份'], densities))}")
            try:
                stat, p = f_oneway(*[[d] for d in densities])
            except Exception:
                stat, p = kruskal(*[[d] for d in densities])
            print(f"年龄组{age_group}网络密度组间差异检验 p值：{p:.3f}")

    end_time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    end_time = time.time()
    print("=" * 40)
    print(f"⌛️ 代码尝试结束 {end_time_str}")
    duration = end_time - start_time
    print(f"总耗时：{int(duration)} 秒（{duration/60:.2f} 分钟）")
    print("=" * 40)

